package com.exam.system.dao;

import com.exam.system.entity.Student;
import com.exam.system.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDAO {

    // 根据学号查询学生信息
    public Student findByStudentId(String studentId) {
        Student student = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM student WHERE student_id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, studentId);
            rs = ps.executeQuery();

            if (rs.next()) {
                student = new Student();
                student.setStudentId(rs.getString("student_id"));
                student.setStudentName(rs.getString("student_name"));
                student.setGender(rs.getString("gender"));
                student.setClassName(rs.getString("class"));
                student.setDepartment(rs.getString("department"));
                student.setMajor(rs.getString("major"));
                student.setPhone(rs.getString("phone"));
                student.setEmail(rs.getString("email"));
                student.setCreateTime(rs.getTimestamp("create_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        return student;
    }

    // 修改学生个人信息
    public boolean updateStudentInfo(Student student) {
        Connection conn = null;
        PreparedStatement ps = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE student SET class=?, department=?, major=?, phone=?, email=? WHERE student_id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, student.getClassName());
            ps.setString(2, student.getDepartment());
            ps.setString(3, student.getMajor());
            ps.setString(4, student.getPhone());
            ps.setString(5, student.getEmail());
            ps.setString(6, student.getStudentId());

            int affectedRows = ps.executeUpdate();
            result = affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps);
        }

        return result;
    }

    // 修改学生密码
    public boolean updatePassword(String studentId, String oldPassword, String newPassword) {
        // 实现密码修改逻辑
        // 注意：密码应该使用加密存储，如MD5、SHA-256等
        return true;
    }
}